﻿using UnityEngine;
using System.Collections;

public class SoundManager : MonoBehaviour {

	public AudioClip[] sounds;
	public AudioClip[] music;

	private static SoundManager soundMan;
	private AudioSource sfxAudio;
	private AudioSource musicAudio;

	void Awake()
	{
		if (soundMan != null) 
		{
			Debug.LogError ("More than  one SoundManager found in the scene");
			return;
		}

		soundMan = this;
		sfxAudio = gameObject.AddComponent<AudioSource> ();	
		musicAudio = gameObject.AddComponent<AudioSource> ();

		sfxAudio.playOnAwake = false;
		musicAudio.playOnAwake = false;
		musicAudio.loop = true;
	}
	/// <summary>
	/// Plaies the sfx.
	/// </summary>
	/// <param name="sfxName">Sfx name.</param>
	public static void PlaySfx(string sfxName)
	{
		if (soundMan == null)
			return;

		soundMan.PlaySound (sfxName, soundMan.sounds, soundMan.sfxAudio);
	}

	public void PlaySound(string soundName, AudioClip[] pool, AudioSource audioOut)
	{
		foreach(AudioClip clip in pool)
		{
			if (clip.name == soundName)
			{
				audioOut.clip = clip;
				audioOut.Play ();
				return;
			}
		}
	}

	public static void PlayMusic(string trackName)
	{
		if (soundMan == null) 
		{
			Debug.LogWarning ("Attempt to play a sound with no SoundManager in the scene");
			return;
		}

		soundMan.musicAudio.time = 0.0f;
		soundMan.musicAudio.volume = 1.0f;

		soundMan.PlaySound (trackName, soundMan.music, soundMan.musicAudio);
	}
	/// <summary>
	/// Pauses the music.
	/// </summary>
	/// <param name="fadeTime">Fade time.</param>
	public static void PauseMusic(float fadeTime)
	{
		if (fadeTime > 0.0f)
			soundMan.StartCoroutine (soundMan.FadeMusicOut (fadeTime));
		else
			soundMan.musicAudio.Pause ();
	}
	/// <summary>
	/// Unpauses the music.
	/// </summary>
	public static void UnpauseMusic()
	{
		soundMan.musicAudio.volume = 1.0f;
		soundMan.musicAudio.Play ();
	}
	/// <summary>
	/// Fades the music out.
	/// </summary>
	/// <returns>The music out.</returns>
	/// <param name="time">Time.</param>
	IEnumerator FadeMusicOut(float time)
	{
		float startVol = musicAudio.volume;
		float startTime = Time.realtimeSinceStartup;

		while (true)
		{
			float t = (Time.realtimeSinceStartup - startTime) / time;
			if (t < 1.0f) {
				musicAudio.volume = (1.0f - t) * startVol;
				yield return 0;
			} else {
				break;
			}
		}
		musicAudio.Pause ();
	}
}
